const mongoose = require('mongoose');
const { nanoid } = require('nanoid');

const tenantSchema = new mongoose.Schema({
  tenantId: {
    type: String,
    required: true,
    unique: true,
    default: () => nanoid(10),
    index: true
  },
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 100
  },
  domain: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
    trim: true,
    match: /^[a-z0-9-]+$/,
    index: true
  },
  email: {
    type: String,
    required: true,
    lowercase: true,
    trim: true,
    match: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  },
  status: {
    type: String,
    enum: ['active', 'inactive', 'suspended', 'pending'],
    default: 'pending'
  },
  plan: {
    type: String,
    enum: ['free', 'basic', 'premium', 'enterprise'],
    default: 'free'
  },
  settings: {
    theme: {
      type: String,
      enum: ['light', 'dark', 'auto'],
      default: 'light'
    },
    language: {
      type: String,
      default: 'en'
    },
    timezone: {
      type: String,
      default: 'UTC'
    },
    features: {
      type: Map,
      of: Boolean,
      default: new Map([
        ['analytics', true],
        ['api_access', true],
        ['custom_branding', false],
        ['advanced_security', false]
      ])
    },
    limits: {
      users: {
        type: Number,
        default: 10
      },
      storage: {
        type: Number,
        default: 1024 // MB
      },
      apiCalls: {
        type: Number,
        default: 1000
      }
    }
  },
  subscription: {
    startDate: {
      type: Date,
      default: Date.now
    },
    endDate: {
      type: Date
    },
    autoRenew: {
      type: Boolean,
      default: true
    },
    paymentMethod: {
      type: String,
      enum: ['credit_card', 'paypal', 'bank_transfer', 'free'],
      default: 'free'
    }
  },
  metadata: {
    type: Map,
    of: mongoose.Schema.Types.Mixed,
    default: new Map()
  }
}, {
  timestamps: true,
  toJSON: { 
    virtuals: true,
    transform: function(doc, ret) {
      delete ret.__v;
      return ret;
    }
  },
  toObject: { virtuals: true }
});

// 虚拟字段：是否为活跃租户
tenantSchema.virtual('isActive').get(function() {
  return this.status === 'active';
});

// 虚拟字段：订阅是否过期
tenantSchema.virtual('isSubscriptionExpired').get(function() {
  if (!this.subscription.endDate) return false;
  return new Date() > this.subscription.endDate;
});

// 虚拟字段：剩余天数
tenantSchema.virtual('daysRemaining').get(function() {
  if (!this.subscription.endDate) return null;
  const now = new Date();
  const endDate = new Date(this.subscription.endDate);
  const diffTime = endDate - now;
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
});

// 索引
tenantSchema.index({ tenantId: 1 }, { unique: true });
tenantSchema.index({ domain: 1 }, { unique: true });
tenantSchema.index({ email: 1 });
tenantSchema.index({ status: 1 });
tenantSchema.index({ createdAt: -1 });

// 静态方法：根据域名查找租户
tenantSchema.statics.findByDomain = function(domain) {
  return this.findOne({ domain: domain.toLowerCase() });
};

// 静态方法：根据租户ID查找
tenantSchema.statics.findByTenantId = function(tenantId) {
  return this.findOne({ tenantId });
};

// 静态方法：获取活跃租户
tenantSchema.statics.findActive = function() {
  return this.find({ status: 'active' });
};

// 实例方法：激活租户
tenantSchema.methods.activate = function() {
  this.status = 'active';
  return this.save();
};

// 实例方法：停用租户
tenantSchema.methods.deactivate = function() {
  this.status = 'inactive';
  return this.save();
};

// 实例方法：暂停租户
tenantSchema.methods.suspend = function() {
  this.status = 'suspended';
  return this.save();
};

// 实例方法：更新设置
tenantSchema.methods.updateSettings = function(newSettings) {
  this.settings = { ...this.settings.toObject(), ...newSettings };
  return this.save();
};

// 实例方法：检查功能是否启用
tenantSchema.methods.hasFeature = function(featureName) {
  return this.settings.features.get(featureName) === true;
};

// 实例方法：启用功能
tenantSchema.methods.enableFeature = function(featureName) {
  this.settings.features.set(featureName, true);
  return this.save();
};

// 实例方法：禁用功能
tenantSchema.methods.disableFeature = function(featureName) {
  this.settings.features.set(featureName, false);
  return this.save();
};

// 实例方法：检查是否达到限制
tenantSchema.methods.isLimitReached = function(limitType, currentUsage) {
  const limit = this.settings.limits[limitType];
  return currentUsage >= limit;
};

// 实例方法：更新订阅
tenantSchema.methods.updateSubscription = function(subscriptionData) {
  this.subscription = { ...this.subscription.toObject(), ...subscriptionData };
  return this.save();
};

// 中间件：保存前验证
tenantSchema.pre('save', function(next) {
  // 确保域名唯一且格式正确
  if (this.isModified('domain')) {
    this.domain = this.domain.toLowerCase().replace(/[^a-z0-9-]/g, '');
  }
  
  // 设置订阅结束日期（如果是付费计划）
  if (this.isModified('plan') && this.plan !== 'free' && !this.subscription.endDate) {
    const endDate = new Date();
    endDate.setMonth(endDate.getMonth() + 1); // 默认一个月
    this.subscription.endDate = endDate;
  }
  
  next();
});

// 中间件：删除前清理相关数据
tenantSchema.pre('deleteOne', { document: true, query: false }, async function(next) {
  try {
    // 删除该租户下的所有用户
    const User = mongoose.model('User');
    await User.deleteMany({ tenantId: this.tenantId });
    
    console.log(`Cleaned up data for tenant: ${this.tenantId}`);
    next();
  } catch (error) {
    next(error);
  }
});

const Tenant = mongoose.model('Tenant', tenantSchema);

module.exports = Tenant;